import * as types from '../types';
import axios from 'axios';
import { findIndex } from 'lodash';

export default {
  state: {
    data: []
  },
  mutations: {
    [types.SET_DEVICES]: (state, payload) => {
      state.data = [];
      for (let i = 0; i != payload.length; ++i) {
        state.data.push(payload[i]);
      }
    },
    [types.RESET_APPS]: (state) => {
      state.data = [];
    },
    [types.ADD_DEVICE]: (state, payload) => {
      state.data.push(payload);
    },
    [types.REMOVE_DEVICE]: (state, devid) => {
      let idx = findIndex(state.data, item => item.devid === devid);
      if (idx === -1) {
        console.error('cannot found deviceid??' + appid);
        return;
      }
      state.data.splice(idx, 1);
    }
  },
  actions: {
    load_devices: ({ commit }, payload) => {
      axios.get('/devices/').then(response => {
        commit(types.SET_DEVICES, response.data);
      }).catch(err => {
        console.log('error occured.');
        console.log(err);
      });
    },
    add_device: ({ commit }, payload) => {
      return new Promise((resolve, reject) => {
        axios.post("/devices/", payload).then(response => {
          commit(types.ADD_DEVICE, response.data);
          resolve(response);
        }).catch(err => {
          console.log('add device server failed');
          console.error(err);
          reject(err);
        });
      });
    },
    remove_device: ({ commit }, devid) => {
      return new Promise((resolve, reject) => {
        axios.delete("/devices/" + devid + "/").then(response => {
          commit(types.REMOVE_DEVICE, devid);
          resolve(response);
        }).catch(err => {
          console.log('remove device error');
          console.error(err);
          reject(err);
        });
      });
    },
  }
}